package hotel.quartz.oversea.job.task;

import com.alibaba.fastjson.JSON;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.constant.CommonUrlConstants;
import hotel.base.oversea.constant.MeituanConstants;
import hotel.base.oversea.constant.quartz.UrlSwitchsEnums;
import hotel.base.oversea.utils.DateUtil;
import hotel.base.oversea.utils.JacksonUtil;
import hotel.base.oversea.utils.Result;
import hotel.base.oversea.utils.SendUtils;
import hotel.quartz.oversea.config.service.RedisService;
import hotel.quartz.oversea.entity.form.JobForm;
import hotel.quartz.oversea.service.JobAndTriggerService;
import hotel.quartz.oversea.util.JobRestTemplateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Slf4j
@Component
public class StartMtApiGoodsPriStatUpdateInfoTask {
    private String timestamp = "Smagpsuit"+String.valueOf(System.currentTimeMillis());

    @Autowired
    private RedisTemplate redisTemplate;

    private String jobGroupName = MeituanConstants.JOB_GROUP_NAME_MT;
    private String jobClassName = this.getClass().getName();

    @Autowired
    private JobAndTriggerService jobAndTriggerService;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RedisService redisService;

    public static void main(String[] args) {
        int min = 3000/80*20/60;
        System.out.printf(""+min);
    }

    /**
     * 一次线程  处理完所有上架酒店  跑所有产品价格房态
     */
    @Async
    public void mtApiGoodsPriStatExecute() {
        log.info("StartMtApiGoodsPriStatUpdateInfoTask {} >>>>>>>> callback主动查询美团价格房态至缓存Task 执行时间: {}", timestamp, DateUtil.getCurrTime());
        if(null != redisTemplate.opsForValue().get("todoUpdatePullMeituanPriceStatusDataCheckToRedisJob_findascuphotelid")){
            log.info("上一个线程获取up的酒店处理中，当前次线程return不做处理");
            return;
        }
        //从缓存中获取上架的酒店
        Long allWaitUpdatePriceHotelDataSize = redisTemplate.opsForList().size(MeituanConstants.REIDS_POP_ALL_SALE_ROOM_ABOUT_MT_HOTEL_IDS);
        if(allWaitUpdatePriceHotelDataSize==0){
            log.info("StartMtApiGoodsPriStatUpdateInfoTask  {} allWaitUpdatePriceHotelDataSize  当前队列size=0，重新获取缓存上架酒店，首轮重新跑批",timestamp, DateUtil.getCurrTime());
            //重置该表示待查询的酒店ids,,opsForList() 每拿出一个hotelID就会集合中剔除一个
            List<Integer> ids = findAscUpMtHotelId();
            if(null != ids && ids.size()>0){
                for (Integer hotelId:ids){
                    redisTemplate.opsForList().leftPush(MeituanConstants.REIDS_POP_ALL_SALE_ROOM_ABOUT_MT_HOTEL_IDS,hotelId);
                }
                allWaitUpdatePriceHotelDataSize = Long.valueOf(ids.size());
            }else{
                log.error("StartMtApiGoodsPriStatUpdateInfoTask {} callback主动查询美团价格房态至缓存Task,redis中无售卖房型的美团酒店id数据，该次定时器主动更新价格推送跳过",timestamp);
            }
        }
        Long allWaitUpdatePriceHotelDataSizeNew = redisTemplate.opsForList().size(MeituanConstants.REIDS_POP_ALL_SALE_ROOM_ABOUT_MT_HOTEL_IDS);
        log.error("StartMtApiGoodsPriStatUpdateInfoTask {} 当前获取到 剩余待查询酒店 allWaitUpdatePriceHotelDataSizeNew：{}",timestamp,allWaitUpdatePriceHotelDataSizeNew);
        if(allWaitUpdatePriceHotelDataSizeNew>0){
            int countTask = MeituanConstants.ALL_TIME_TASK_COUNT;
            if(null != redisTemplate.opsForValue().get("allTimeQueryUpHotelPriceStatus_count_task")){
                countTask = (Integer) redisTemplate.opsForValue().get("allTimeQueryUpHotelPriceStatus_count_task");
            }
            Integer sleeptime = 60000;
            if(null != redisTemplate.opsForValue().get("mtApiGoodsPriStatExecute_sleeptime_sec")){
                sleeptime = (Integer) redisTemplate.opsForValue().get("mtApiGoodsPriStatExecute_sleeptime_sec");
                //2000 * 10  让task间隔20秒调一次，由于携程处理不过来，队列堆积太多，不然后面的异步通知都只能延迟处理
                //每调用一次美团方法，方法内部发起8个线程，1个线程涉及10个酒店，则总共处理80个酒店，则追加队列数据为80条。  每间隔14秒80条
                //携程是2秒处理8条左右，则20秒处理80个队列左右
            }
            Long min = 1L;
            if(allWaitUpdatePriceHotelDataSizeNew/(countTask*10)>0){
                min = allWaitUpdatePriceHotelDataSizeNew/(countTask*10)*(sleeptime/1000)/60;
            }
            if(min>1){
                redisTemplate.opsForValue().set("todoSwitchsGetChangeRedisDataToPushJob_todo_mtquerypristat","1",min.intValue()+1, TimeUnit.MINUTES);
            }

            log.info("mtApiGoodsPriStatExecute 存在上架酒店 size={},缓存失效时间min={},sleeptime={},countTask={}",allWaitUpdatePriceHotelDataSizeNew,min,sleeptime,countTask);
            long count = allWaitUpdatePriceHotelDataSizeNew/(10*countTask);
            if(allWaitUpdatePriceHotelDataSizeNew%(10*countTask)>0){
                count += 1;
            }
            log.info("allWaitUpdatePriceHotelDataSizeNew count={}",count);
            for (int i = 0; i < count; i++) {
                if(null != redisTemplate.opsForValue().get("mtApiGoodsPriStatExecute_sleeptime_sec")){
                    sleeptime = (Integer) redisTemplate.opsForValue().get("mtApiGoodsPriStatExecute_sleeptime_sec");
                    //2000 * 10  让task间隔20秒调一次，由于携程处理不过来，队列堆积太多，不然后面的异步通知都只能延迟处理
                    //每调用一次美团方法，方法内部发起8个线程，1个线程涉及10个酒店，则总共处理80个酒店，则追加队列数据为80条。  每间隔14秒80条
                    //携程是2秒处理8条左右，则20秒处理80个队列左右
                }
                log.info("allWaitUpdatePriceHotelDataSizeNew 调用美团方法i={},调用前 hotel队列size={},该size不代表真实因为异步线程在实时处理中",i,redisTemplate.opsForList().size(MeituanConstants.REIDS_POP_ALL_SALE_ROOM_ABOUT_MT_HOTEL_IDS));

                req(1);

                if(redisTemplate.opsForList().size(MeituanConstants.REIDS_POP_ALL_SALE_ROOM_ABOUT_MT_HOTEL_IDS)==0){
                    log.info("StartMtApiGoodsPriStatUpdateInfoTask 缓存的酒店为0 break");
                    break;
                }
                try {
                    Thread.sleep(sleeptime);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
                if(null != redisTemplate.opsForValue().get("mt_query_price_status_stop")){
                    log.info("主动查询停止多线程跑美团酒店");
                    break;
                }

            }
        }
        redisTemplate.delete("todoSwitchsGetChangeRedisDataToPushJob_todo_mtquerypristat");
        log.info("StartMtApiGoodsPriStatUpdateInfoTask {} >>>>>>>> callback主动查询美团价格房态至缓存Task 结束时间: {},{}",timestamp, DateUtil.getCurrTime());

    }
    private Integer req(Integer count){
        if(count>100){
            request();
            return 1;
        }
        if(redisTemplate.opsForList().size(MeituanConstants.REDIS_CHANGE_GOODS_DATA_MANY_HOTEL)>30){
            log.info("队列中待消费大于30，当前延迟发起多线程主动查询酒店 count={}",count);
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            return req(count+1);
        }else{
            request();
        }
        if(count==1){
            try {
                Thread.sleep(2);//线程也可能并发
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return 1;

    }

    private List<Integer> findAscUpMtHotelId() {
        redisTemplate.opsForValue().set("todoUpdatePullMeituanPriceStatusDataCheckToRedisJob_findascuphotelid",1,2, TimeUnit.SECONDS);
        String switchHost = CommonUrlConstants.SWITCHS_HOST;
        String getUpMtHotel = switchHost+ UrlSwitchsEnums.checkFindPriceStatus.GET_UP_MT_HOTEL.getValue();
        log.info("StartMtApiGoodsPriStatUpdateInfoTask {} callback主动查询美团价格房态至缓存Task 进入方法 findAscUpMtHotelId",timestamp);
        //发起请求
        Map params = new HashMap();
        params.put("timestamp",timestamp);//每次定时器调用接口传唯一timestamp，为了方便查询线程日志
        Result response = JobRestTemplateUtils.post(getUpMtHotel, JSON.toJSONString(params),restTemplate);
        if(response.getCode()== CommonConstants.SUCCESS){
            List<Integer> list = JacksonUtil.objToBean(response.getData(), List.class);
            return list;
        }
        redisTemplate.delete("todoUpdatePullMeituanPriceStatusDataCheckToRedisJob_findascuphotelid");
        return null;
    }

    /**
     * 调用美团接口    主动查询上送的酒店是否存在变动数据，有则接口中操作存入缓存队列
     *
     * @return
     */
    private void request() {
        String callbackHost = CommonUrlConstants.CALLBACK_HOST;
        String checkGetChangeGoodsByOneHotelUrl = callbackHost+ UrlSwitchsEnums.goodsPrice.CHECK_GET_CHANGE_GOODSIDS_BY_ONE_HOTEL_NEW.getValue();
        log.info("StartMtApiGoodsPriStatUpdateInfoTask {} callback主动查询美团价格房态至缓存Task 进入方法 request",timestamp);
        //发起请求
        Map params = new HashMap();
        params.put("timestamp",timestamp);//每次定时器调用接口传唯一timestamp，为了方便查询线程日志

        long size = redisTemplate.opsForList().size(MeituanConstants.REIDS_POP_ALL_SALE_ROOM_ABOUT_MT_HOTEL_IDS);
        log.info("StartMtApiGoodsPriStatUpdateInfoTask {} callback主动查询美团价格房态至缓存Task  调用携程接口前，缓存酒店队列size={}",timestamp,size);
        Result response = JobRestTemplateUtils.post(checkGetChangeGoodsByOneHotelUrl, JSON.toJSONString(params),restTemplate);
        if(response.getCode()== CommonConstants.SUCCESS){
        }else{
            //还原
            //redisTemplate.opsForList().leftPush(MeituanConstants.REIDS_POP_ALL_SALE_ROOM_ABOUT_MT_HOTEL_IDS,String.valueOf(hotelId));
            log.error("StartMtApiGoodsPriStatUpdateInfoTask {} callback主动查询美团价格房态至缓存Task进入方法 request 返回失败：{},{}",timestamp, JSON.toJSONString(response), JSON.toJSONString(params));
        }
        long size2 = redisTemplate.opsForList().size(MeituanConstants.REIDS_POP_ALL_SALE_ROOM_ABOUT_MT_HOTEL_IDS);
        log.info("StartMtApiGoodsPriStatUpdateInfoTask {} callback主动查询美团价格房态至缓存Task  调用携程接口结束，缓存酒店队列size={}",timestamp,size2);
    }
    public void cronJob(String cron,String doTime){
        //已最后一页，暂停定时器,删除rediskey
        JobForm jobForm = new JobForm();
        jobForm.setJobClassName(jobClassName);
        jobForm.setJobGroupName(jobGroupName);
        jobForm.setCronExpression(cron);
        try {
            jobAndTriggerService.cronJob(jobForm);
            log.info("StartMtApiGoodsPriStatUpdateInfoTask 程序触发n"+doTime+"秒后继续执行");
        } catch (Exception e) {
            log.error("StartMtApiGoodsPriStatUpdateInfoTask {} 执行cronJob异常: {}",timestamp,jobForm);
            log.error(e.getMessage(),e);
            try {
                Thread.sleep(5000);
                log.error("StartMtApiGoodsPriStatUpdateInfoTask {} 再次执行cronJob",timestamp);
                jobAndTriggerService.cronJob(jobForm);
            } catch (Exception e2) {
                log.error(e2.getMessage(), e2);
                SendUtils.dingMsg("【异步处理美团房态定时器出现异常，请核实！】", e2.getMessage(),99,restTemplate);
            }
        }
    }


}
